from starlette.types import ASGIApp, Receive, Scope, Send
from starlette.requests import Request
from starlette.responses import JSONResponse
import logging
from urllib import parse
from ..dto.Result import Result


from ..utils.JwtUtils import JwtUtils
from ..utils.ExcludeUrl import ExcludeUrl


class RequestInterceptionMiddleware:
    """
    用来拦截请求的第一层中间件
    主要用来检查jwt令牌
    """

    def __init__(self, app: ASGIApp):
        self.app = app

    async def __call__(self, scope: Scope, receive: Receive, send: Send):
        if scope["type"] == "http":
            request = Request(scope)
            logging.info(f"拦截到请求: {str(request.url)}")
            if ExcludeUrl.isExclude(request.url.path):
                await self.app(scope, receive, send)
                return

            jwt = request.headers.get("token")
            try:
                data = JwtUtils.decode(jwt)
            except Exception as e:
                logging.info("jwt无效")
                response = JSONResponse(
                    content=Result.error("NOT_LOGIN").model_dump(), status_code=200
                )
                await response(scope, receive, send)
                return
            logging.info("jwt有效")
        await self.app(scope, receive, send)
